import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ywn_app/contains/ThemeGlobal.dart';
import 'package:http/http.dart' as http;
import 'package:ywn_app/custom/PlayVideo.dart';

class MovieDetails extends StatefulWidget {
  final String id;
  final String playUrl;
  final String title;
  final String fmplaycnt;
  final String publishTime;
  final String fmplaycnt2;
  final String fmlike;

  MovieDetails(
      {Key key,
      this.playUrl,
      this.id,
      this.title,
      this.publishTime,
      this.fmplaycnt,
      this.fmplaycnt2,
      this.fmlike})
      : super(key: key);

  @override
  _MovieDetailsState createState() => _MovieDetailsState();
}

class _MovieDetailsState extends State<MovieDetails>
    with SingleTickerProviderStateMixin {
  TabController tabController;

  Map<String, dynamic> data;
  List list = [];
  String commentCount;
  List commentList = [];

  @override
  void initState() {
    super.initState();
    this.tabController = TabController(length: 2, vsync: this);
    _getData();
    _commentGetData();
  }

  void _getData() async {
    await http
        .get(
            'https://haokan.baidu.com/videoui/api/videoauthor?vid=' + widget.id)
        .then((http.Response response) {
      setState(() {
        data = json.decode(response.body)['data']['response'];
      });
    });
    _pullNet();
  }

  void _pullNet() async {
    await http
        .get(
            'https://haokan.baidu.com/videoui/api/videorec?tab=xiaopin&act=pcFeed&pd=pc&num=30')
        .then((http.Response response) {
      Map<String, dynamic> user = json.decode(response.body);
      setState(() {
        list = user['data']['response']['videos'];
      });
    });
  }

  void _commentGetData() async {
    await http
        .get(
        'https://haokan.baidu.com/videoui/api/commentget?rn=10&url_key='+widget.id+'&pn=1&child_rn=2')
        .then((http.Response response) {
      Map<String, dynamic> user = json.decode(response.body);
      setState(() {
        commentCount = user['data']['comment_count'];
        commentList = user['data']['list'];
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor,
      body: CustomScrollView(
        physics: NeverScrollableScrollPhysics(),
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: PlayVideo(url: widget.playUrl,title: widget.title,timer: 5000,id: widget.id,),
          ),
          SliverPersistentHeader(
            pinned: false,
            delegate: StickyTabBarDelegate(
                child: TabBar(
              indicatorColor: themeColor,
              indicatorSize: TabBarIndicatorSize.label,
              labelColor: themeColor,
              controller: this.tabController,
              unselectedLabelColor: Colors.black54,
              tabs: <Widget>[
                Tab(text: '详情'),
                Tab(text: '评论('+commentCount+')'),
              ],
            )),
          ),
          SliverFillRemaining(
            child: TabBarView(
              controller: this.tabController,
              children: <Widget>[
                Padding(
                    padding: EdgeInsets.only(top: 10,left: 10,right: 10,bottom: 10),
                    child: Scaffold(
                      backgroundColor: backgroundColor,
                      body: CustomScrollView(
                        slivers: <Widget>[
                          SliverToBoxAdapter(
                              child: data != null
                                  ? Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      mainAxisSize: MainAxisSize.min,
                                      children: <Widget>[
                                        Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Container(
                                              margin: EdgeInsets.only(right: 5),
                                              height: 40,
                                              child: ClipOval(
                                                child: Image.network(
                                                    data['author']
                                                        ['author_icon']),
                                              ),
                                            ),
                                            Column(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Text(
                                                  data['author']['author'],
                                                  style: TextStyle(
                                                      color: themeColor,
                                                      fontSize: 14,
                                                      fontWeight:
                                                          FontWeight.bold),
                                                ),
                                                Row(
                                                  children: <Widget>[
                                                    Text(
                                                      data['author'][
                                                          'authentication_content'],
                                                      style: TextStyle(
                                                          color: Colors.black45,
                                                          fontSize: 12),
                                                    ),
                                                    SizedBox(
                                                      width: 5,
                                                    ),
                                                    Text(
                                                        data['cnt']
                                                            ['fansCntText'],
                                                        style: TextStyle(
                                                            color:
                                                                Colors.black38,
                                                            fontSize: 12)),
                                                  ],
                                                )
                                              ],
                                            )
                                          ],
                                        ),
                                        Container(
                                          width: 50,
                                          height: 25,
                                          decoration: BoxDecoration(
                                              color: themeColor,
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(3))),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: <Widget>[
                                              Icon(
                                                Icons.add,
                                                color: Colors.white,
                                                size: 14,
                                              ),
                                              Text(
                                                '关注',
                                                style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 12),
                                              )
                                            ],
                                          ),
                                        )
                                      ],
                                    )
                                  : SizedBox.shrink()),
                          SliverToBoxAdapter(
                              child: Padding(
                                  padding: EdgeInsets.only(top: 8),
                                  child: Text(widget.title,
                                      textAlign: TextAlign.start,
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          fontSize: 15,
                                          fontWeight: FontWeight.w400)))),
                          SliverToBoxAdapter(
                              child: Padding(
                                  padding: EdgeInsets.only(top: 5),
                                  child: Row(
                                    children: <Widget>[
                                      BottomTitle(
                                        icon: Icons.play_circle_outline,
                                        num: widget.fmplaycnt2,
                                      ),
                                      SizedBox(
                                        width: 10,
                                      ),
                                      BottomTitle(
                                        icon: Icons.favorite_border,
                                        num: widget.fmlike + '喜欢',
                                      ),
                                      SizedBox(
                                        width: 10,
                                      ),
                                      BottomTitle(
                                        icon: Icons.access_time,
                                        num: widget.publishTime,
                                      ),
                                    ],
                                  ))),
                          SliverToBoxAdapter(
                              child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Padding(padding: EdgeInsets.only(top: 10,bottom: 10),child: Divider(
                                        height: 3,
                                        color: Colors.black12,
                                      ),),
                                      Text(
                                        '猜你喜欢',
                                        style: TextStyle(
                                            fontSize: 16,
                                            fontWeight: FontWeight.bold),
                                      )
                                    ],
                                  )),
                          SliverList(
                              delegate:
                                  SliverChildBuilderDelegate((context, int i) {
                            return GuessLike(
                                title: list[i]['title'],
                                sourceName: list[i]['source_name'],
                                posterSmall: list[i]['poster_small'],
                                fmlike: list[i]['fmlike'],
                                fmplaycnt: list[i]['fmplaycnt_2'],
                                duration: list[i]['duration'],
                                playUrl: list[i]['play_url'],
                                id: list[i]['id'],
                                publishTime: list[i]['publish_time'],
                                fmplaycnt2: list[i]['fmplaycnt']);
                          }, childCount: list.length))
                        ],
                      ),
                    )),

                Padding(
                  padding: EdgeInsets.only(left: 10,right: 10,bottom: 10,top: 10),
                  child: Scaffold(
                    backgroundColor: backgroundColor,
                    body: CustomScrollView(
                      slivers: <Widget>[
                        SliverToBoxAdapter(
                          child: Container(
                            margin: EdgeInsets.only(bottom: 10),
                            child: Text(commentCount+'条评论',
                              style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16,color: Colors.black87)),
                          ),
                        ),
                        SliverList(
                            delegate: SliverChildBuilderDelegate(
                                    (context, int i){
                          return Container(
                            padding: EdgeInsets.only(top: 10,bottom: 10),
                            decoration: BoxDecoration(
                                border: Border(
                                    bottom: BorderSide(width: 1,color: Colors.black12)
                                )
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Row(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: <Widget>[
                                        Container(
                                          width: 40,
                                          child: ClipOval(
                                            child: Image.network(
                                              commentList[i]['avatar'],
                                            ),
                                          ),
                                        ),
                                        SizedBox(
                                          width: 5,
                                        ),
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text(commentList[i]['uname'],
                                                style: TextStyle(color: Theme.of(context).primaryColor,fontSize: 14,fontWeight: FontWeight.bold)),
                                            Text(commentList[i]['create_time_text'],style: TextStyle(color: Colors.black38,fontSize: 12),),
                                          ],
                                        ),
                                      ],
                                    ),
                                    Row(
                                      children: <Widget>[
                                        Text(commentList[i]['like_count'],style: TextStyle(
                                          color: Colors.black45
                                        ),),
                                        SizedBox(width: 3),
                                        InkWell(
                                          child: Icon(Icons.favorite_border,color: Colors.red,size: 20,),
                                          onTap: (){
                                            print(commentList[i]['content']);
                                          },
                                        )
                                      ],
                                    ),
                                  ],
                                ),
                                Text(commentList[i]['content'],style: TextStyle(
                                  color: Colors.black,fontSize: 16
                                )),
                                SizedBox(
                                  height: 5,
                                ),
                                Container(
                                  alignment: Alignment.center,
                                  width: 50,
                                  height: 20,
                                  decoration: BoxDecoration(
                                    color: Colors.black12,
                                    borderRadius: BorderRadius.circular(3)
                                  ),
                                  child: InkWell(
                                    child: Text('回复'),
                                    onTap: (){
                                      print("dwesfwef");
                                    },
                                  ),
                                )

                              ],
                            ),
                          );
                        },
                          childCount: commentList.length
                        )),
                      ],
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}

class GuessLike extends StatelessWidget {
  final String id;
  final String title;
  final String posterSmall;
  final String sourceName;
  final String duration;
  final String fmplaycnt;
  final String fmlike;
  final String playUrl;
  final String publishTime;
  final String fmplaycnt2;

  GuessLike(
      {Key key,
      this.id,
      this.duration,
      this.title,
      this.fmlike,
      this.fmplaycnt,
      this.playUrl,
      this.fmplaycnt2,
      this.posterSmall,
      this.publishTime,
      this.sourceName})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Container(
        padding: EdgeInsets.only(top: 10),
        height: 100,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              height: 100,
              width: 140,
              alignment: Alignment.bottomRight,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5),
                image: DecorationImage(
                  image: NetworkImage(posterSmall),
                  fit: BoxFit.cover,
                ),

              ),
              child: Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Colors.black38,
                      borderRadius: BorderRadius.circular(3)
                  ),
                  width: 50,
                  height: 25,
                  margin: EdgeInsets.only(right: 5,bottom: 5),
                  child: Text(duration,style: TextStyle(color: Colors.white,fontSize: 14),)
              ),
            ),
            SizedBox(width: 10,),
            Expanded(child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Text(title,style: TextStyle(fontSize: 14),maxLines: 2,overflow: TextOverflow.ellipsis,),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Icon(Icons.person_outline,size: 20,color: Colors.black45,),
                    Text(sourceName,style: TextStyle(color: Colors.black45),)
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Icon(Icons.play_circle_outline,size: 18,color: Colors.black45),
                        Text(fmplaycnt,style: TextStyle(color: Colors.black45,fontSize: 12),)
                      ],
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        fmlike!=''?Icon(Icons.favorite_border,size: 18,color: Colors.black45):SizedBox.shrink(),
                        Text(fmlike,style: TextStyle(color: Colors.black45,fontSize: 12),)
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        Icon(Icons.more_vert,size: 18,color: Colors.black45),
                      ],
                    )
                  ],
                )
              ],
            ))
          ],
        ),
      ),
      onTap: (){
        Navigator.pop(context);
        Navigator.push(context,MaterialPageRoute(builder: (BuildContext context) => MovieDetails(
          id: this.id,
          playUrl: this.playUrl,
          title: this.title,
          publishTime:this.publishTime,
          fmplaycnt: this.fmplaycnt,
          fmplaycnt2:this.fmplaycnt2,
          fmlike: this.fmlike,
        )));
      },
    );
  }
}


class BottomTitle extends StatelessWidget {
  final IconData icon;
  final String num;
  BottomTitle({Key key, this.num, this.icon}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        Icon(
          icon,
          size: 18,
          color: Colors.black38,
        ),
        Text(
          num,
          style: TextStyle(fontSize: 12, color: Colors.black38),
        )
      ],
    );
  }
}

class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar child;

  StickyTabBarDelegate({@required this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return this.child;
  }

  @override
  double get maxExtent => this.child.preferredSize.height-20;

  @override
  double get minExtent => this.child.preferredSize.height-20;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}
